<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;
use Common\ORG\Page,Common\ORG\AttUpload,Common\ORG\Excel;
/*
 * 合同管理
 */
class ContractController extends BaseController {

	//合同首页
	public function index(){
		$export   = I('get.export', '', 'intval');
		$res      = array('rcode'=>1,'contract'=>NULL, 'msg'=> 'OK');
		$psize    = I('get.psize', $this->m_psize,'intval');
		$p        = I('get.p', '','intval');
		$pall     = I('get.pall');
		$psize    = (!$psize || $psize>$this->m_psize ) ? $this->m_psize:$psize ;

		$where    = array();
		$maps     = array();
		$where['_string']            = '1=1';
		$where['contract.is_delete'] = array('neq', 1 );
		//搜索条件
		$customer = I('get.customer');
		if($customer && !empty($customer)){
			if(strlen($customer) > 3 && is_numeric($customer))  $maps['customer.phone'] = array('like','%'.$customer.'%');
			$maps['customer.nickname']      = array('like','%'.$customer.'%');
			$maps['customer.customer_code'] = array('like','%'.$customer.'%');
			$maps['_logic']    = 'OR';
			$where['_complex'] = $maps;
		}

		$saless    = I('get.sales');
		if($saless){
			$where['user.nickname'] = array('like','%'.$saless.'%');
		}

		$product  = I('get.product');
		if($product && $product!="-1" ){
			$where['product.product_id'] = $product;
		}

		$stime    = I('get.first_time','','trim');
		$etime    = I('get.second_time','','trim');

		if( $stime && $etime ){
			$stime = date('Y-m-d 00:00:00',strtotime($stime));
			$etime = date('Y-m-d 23:59:59', strtotime($etime));
			if(strtotime($stime) < strtotime($etime)) $where['contract.start_time'] = array('between',array($stime,$etime));
			else $where['contract.start_time'] = array('between',array($etime,$stime));
		}elseif($stime  && !$etime ){
			$stime = date('Y-m-d 00:00:00',strtotime($stime));
			$where['contract.start_time'] =  array('egt',$stime);
		}elseif(!$stime && $etime ){
			$etime = date('Y-m-d 23:59:59', strtotime($etime));
			$where['contract.start_time'] = array('elt', $etime);
		}

		$state = I('get.state');
		if(5== $state || empty( $state)){
			$where['contract.state']  = array('between', array('-2', '5' ) );
		}elseif(6== $state){
			$where['contract.state'] = array('eq', '0' );
		}else{
			$where['contract.state'] = array('eq', $state );
		}

		if($export){
			$ServiceUser = D("Admin/User","Service","Admin");
            $r_export =$ServiceUser->authWithKey( $this->m_user['user_id'], 'CONTRACT_EXPORT');
             if (!$r_export['rcode'] ) {
                $res['msg'] = "无权导出数据";
            }else{
            	$header   = array('签订金额','客户姓名','电话','产品类型','服务期限','合同开始时间','合同是否签好','合同时长','合同编号','邮寄地址','业务员','经理','团队','身份证号','是否违规','违规原因','备注','甲方账户名','账号','开户银行','地址','乙方姓名','身份证号','电话','地址','邮编');
				$contract = M("contract")
						->field("contract.contract_id,contract.mount,contract.end_time,contract.start_time,contract.state,contract.order_num,contract.address,contract.sales_person,contract.sales_manager,contract.sales_sub_company,contract.second_party_idcard,contract.remark,contract.weigui_status,customer.nickname as customer_name,customer.phone,product.name,contract.first_party_name,contract.first_party_bank_account,contract.first_party_bank_deposit,contract.first_party_address,contract.second_party_name,contract.second_party_phone,contract.second_party_idcard,contract.second_party_address,contract.second_party_email")
						->join("LEFT JOIN customer ON contract.customer_id = customer.customer_id")
						->join("LEFT JOIN product  ON contract.product_id  = product.product_id")
						->join("LEFT JOIN user     ON contract.sales_person= user.user_id")
						->where($where)
						->order("contract.contract_id desc")
						->select();
			
                $row   = array();
                $MExcel= new Excel();
                $Sheet = new \Common\ORG\Sheet("合同数据");
                $Sheet->setColumn( array_values( $header) );
                foreach ($contract as $val ) {
                   //合同时长计算
					$length['contract_id'] = $val['contract_id'];
					$length['source_type'] = 1;
					$delivery = M("delivery")->field("status,send_time")->order("delivery_id desc")->find();
					if($delivery['status'] == 2){
						$results = ceil((strtotime($delivery['send_time'])-strtotime($val['start_time']))/(3600*24));
					}elseif($delivery['status'] == 1){
						$results = ceil((strtotime(date("Y-m-d H:i:s"))-strtotime($val['start_time']))/(3600*24));
					}else{
						$results = '';
					}
					//业务员
					$sales['user_id']  = $val['sales_person'];
					$user    = M("user")->field("nickname")->where($sales)->find();
					//经理
					$sector['user_id'] = $val['sales_manager'];
					$manager = M("user")->field("nickname")->where($sector)->find();
					//团队
					$team['sector_id'] = $val['sales_sub_company'];
					$company = M("sector")->field("sector_name")->where($team)->find();

					//违规原因
					$violations['contract_id'] = $val['contract_id'];
					$fine  = M("fine")->field("theme")->where($violations)->order("fine_id")->find();

					if($fine && $fine['theme'] == 1)      $fine['theme'] = '不签署合同';
					elseif($fine && $fine['theme'] == 2)  $fine['theme'] = '暂不寄';
					elseif($fine && $fine['theme'] == 3)  $fine['theme'] = '超龄';
					elseif($fine && $fine['theme'] == 4)  $fine['theme'] = '虚假身份';
					else  $fine['theme'] = '';

					$row['mount'] = $val['mount'];
					$row['customer_name'] = $val['customer_name'];
					$row['phone'] = ' '.$val['phone'];
					$row['name'] = $val['name'];
					$row['end_time'] = date("Y-m-d",strtotime($val['end_time']));
					$row['start_time'] = date("Y-m-d",strtotime($val['start_time']));
					$row['state'] = $val['state'] == 1?'已签好':($val['state'] == 3?'已签好':'未知');
					$row['long_time'] = $results;//时长计算
					$row['order_num'] = $val['order_num'];
					$row['address'] = $val['address'];
					$row['nickname'] = $user['nickname'];//业务员
					$row['manager_nickname'] = $manager['nickname'];//经理
					$row['sector_name'] = $company['sector_name'];//团队
					$row['second_party_idcard'] = $val['second_party_idcard'];
					$row['weigui_status'] = $val['weigui_status'] == 0?'未知':($val['weigui_status'] == 21?'不违规':($val['weigui_status'] == 11?'违规未导出':'违规已导出'));
					$row['theme'] = $fine['theme'];//违规原因
					$row['remark'] = $val['remark'];

					$row['first_party_name'] = $val['first_party_name'];
					$row['first_party_bank_account'] = $val['first_party_bank_account'];
					$row['first_party_bank_deposit'] = $val['first_party_bank_deposit'];
					$row['first_party_address'] = $val['first_party_address'];
					$row['second_party_name'] = $val['second_party_name'];
					$row['second_party_idcard'] = ' '.$val['second_party_idcard'];
					$row['second_party_phone'] = ' '.$val['second_party_phone'];
					$row['second_party_address'] = $val['second_party_address'];
					$row['second_party_email'] = $val['second_party_email'];

	               $Sheet->addRow( array_values($row) );
                }

                $MExcel->add_sheet( $Sheet );
                $exportRet = $MExcel->export_sheet("合同数据");
                if( $exportRet['rcode'] ){
                    $res['rcode'] = 1;
                    $res['data'] = $exportRet['data'];
                    $res['msg'] = 'OK';
                }
                else
                    $res['msg'] = $exportRet['msg'];
            }
		}else{	
			//列表数据
			$Contract = M("contract");
			$count 	  = $Contract
						->join(" LEFT JOIN product  ON contract.product_id  = product.product_id ")
						->join(" LEFT JOIN customer ON contract.customer_id = customer.customer_id ")
						->join(" LEFT JOIN user     ON contract.sales_person= user.user_id ")
						->where( $where )
						->count();
			$Page      = new \Common\ORG\Page( $count, $psize );
			$contract  = $Contract->field("contract.type,contract.contract_id,contract.address as contract_address,contract.sign_status,contract.teacher_cert,
										   contract.weigui_status,contract.is_refund,contract.is_need_combine,contract.order_num as contract_order,
										    contract.need_return_visit,contract.start_time,contract.end_time,contract.product_id,contract.order_num,
											contract.mount,contract.state,contract.sales_person,contract.sales_manager,contract.sales_sub_company,
											contract.sales_sector,contract.remark as contract_remark,contract.content,contract.is_need_combine,contract.title,contract.first_party_name,
											contract.first_party_address,contract.first_party_bank_account,contract.first_party_bank_deposit,contract.is_refund,
											contract.second_party_name,contract.second_party_email,contract.second_party_phone,contract.second_party_idcard,contract.second_party_address,
											customer.customer_id,customer.mount as customer_mount,customer.nickname,customer.customer_code,customer.phone,customer.location,customer.address,
											customer.remark ,product.product_id,product.name")
									->join(" LEFT JOIN product  ON contract.product_id  = product.product_id ")
									->join(" LEFT JOIN customer ON contract.customer_id = customer.customer_id ")
									->join(" LEFT JOIN user     ON contract.sales_person= user.user_id ")
									->where($where)
									->order("contract.contract_id desc")
									->limit($Page->firstRow.','.$Page->listRows )
									->select();
			foreach($contract as &$value){
				//时间处理
				$value['mount']      = floor($value['mount']);
				$value['capital_mouhnt'] = D("Contract")->ParseNumber($value['mount']);
				$value['customer_mount'] = sprintf('%.2f', $value['customer_mount']);
				$value['start_time'] = date("Y-m-d",strtotime($value['start_time']));
				$value['date']       = date('Y'.'年'.'m'.'月'.'d'.'日',strtotime($value['start_time']));
				$value['end_time']   = date("Y-m-d",strtotime($value['end_time']));
				//团队
				$team['sector_id']   = $value['sales_sub_company'];
				$company = M("sector")->field("sector_id,sector_name")->where($team)->find();
				$value['company_name']    = $company['sector_name'];
				$value['company_id']      = $company['sector_id'];
				//经理
				$sector['user_id']   = $value['sales_manager'];
				$manager = M("user")->field("user_id,nickname")->where($sector)->find();
				$value['manager']    = $manager['nickname'];
				$value['manager_id'] = $manager['user_id'];
				//负责人
				$sales['user_id']    = $value['sales_person'];
				$user_    = M("user")->field("user_id,nickname")->where($sales)->find();
				$value['user_name']  = $user_['nickname'];
				$value['user_id']    = $user_['user_id'];
				//最后付款流水id
				$payContract['contract_id'] = $value['contract_id'];
				$pay = M("pay_record")->field("payrecord_id,pay_order")->where($payContract)->order("payrecord_id desc")->find();
				$value['payrecord_id']= $pay['payrecord_id'];
				$value['payrecord_order']= $pay['pay_order'];
			}

			if( $contract ){
				$res['rcode']    = 1;
				$res['contract'] = $contract;
				$res['pall']     =  $pall == ''?$Page->getTotalPages():$pall;
				$res['p']        =  $p ==''?$Page->nowPage:$p;
				$res['psize']    = $psize;
				$res['count']    = $count;
			}
		}
		e_json( $res );
	}
	//扫描和同
	public function sweepContract(){
		$sweep['contract.order_num'] = I("order_num");
		$contract = M("contract")
				->field("contract.contract_id,contract.start_time,contract.address,contract.end_time,contract.mount,contract.product_id,contract.state,contract.sales_person,contract.sales_manager,contract.sales_sub_company,contract.sales_sector,contract.customer_id,customer.nickname as customer_name,customer.phone,product.name")
				->join("LEFT JOIN customer ON contract.customer_id  = customer.customer_id")
				->join("LEFT JOIN product  ON contract.product_id   = product.product_id")
				->where($sweep)
				->find();
		if($contract){
			//信息处理
			$contract['start_time'] = date("Y-m-d",strtotime($contract['start_time']));
			$contract['end_time']   = date("Y-m-d",strtotime($contract['end_time']));
			$contract['mount']      = floor($contract['mount']);
			$contract['sector_id']  = $contract['sales_sector'];
			$contract['manager_id'] = $contract['sales_manager'];
			//服务人员
			$where['user_id'] = $contract['sales_person'];
			$user = M("user")->field("nickname")->where($where)->find();
			$contract['user_name']  = $user['nickname'];
			$contract['user_id']    = $contract['sales_person'];
			//所属团队
			$wheres['sector_id'] = $contract['sales_sub_company'];
			$sector = M("sector")->field("sector_id,sector_name")->where($wheres)->find();
			$contract['company_name'] = $sector['sector_name'];
			$contract['company_id']   = $sector['sector_id'];
			$res['rcode'] = 1;
			$res['sweep'] = $contract;
		}else{
			$res['rcode'] = 2;
		}
		e_json($res);
	}
	//合同编号扫码监测
	public function sweepDetection(){
		$sweep['contract.order_num'] = I("order_num");
		$contract = M("contract")
				->field("contract.contract_id,contract.start_time,contract.address,contract.end_time,contract.mount,contract.product_id,contract.state,contract.sales_person,contract.sales_manager,contract.sales_sub_company,contract.sales_sector,contract.customer_id,customer.nickname as customer_name,customer.phone,product.name")
				->join("LEFT JOIN customer ON contract.customer_id  = customer.customer_id")
				->join("LEFT JOIN product  ON contract.product_id   = product.product_id")
				->where($sweep)
				->find();
		if($contract){
			$res['rcode'] = 1;
		}else{
			$res['rcode'] = 2;
		}
		e_json($res);
	}
	//合并和同加载
	public function merge_show(){

		$customer      = I('get.customer');
		$customer_code = I('get.customer_id');
		if($customer && $customer_code){
			$where = array();
			$where['customer.customer_code']   = array('eq',$customer);
			$where['contract.customer_id']     = array('eq',$customer_code );
			$where['_logic'] = 'or';
			$map['_complex'] = $where;
		}else{
			$map['contract.customer_id']       = $customer_code;
		}

		$map['contract.is_delete']     = array('neq','1');
		$map['contract.state']         = array(array('neq','2'),array('neq','-1'),'and');
		$merge_contract = M('contract')
						->field("contract.contract_id,contract.mount,contract.weigui_status,contract.order_num,contract.remark,contract.state,contract.start_time,contract.end_time,contract.sales_person,contract.sales_sector,contract.sales_manager,contract.sales_sub_company,user.nickname as user_name,user.user_id,user.sector_id,product.name,product.product_id,customer.customer_id,customer.nickname as customer_name,customer.phone")
						->join("LEFT JOIN user     ON contract.sales_person = user.user_id")
						->join("LEFT JOIN customer ON contract.customer_id  = customer.customer_id")
						->join("LEFT JOIN product  ON contract.product_id   = product.product_id")
						->where($map)
						->order("contract.contract_id desc")
						->select();
		$Ssector      = M("sector");
		foreach($merge_contract as &$value){
			if($value['customer_code'] == $customer){
				$list[] = $value;
			}
			$value['mount']       = floor($value['mount']);

			//时间处理
			$value['start_time']  = substr($value['start_time'], 0,10);
			$value['end_time']    = substr($value['end_time'], 0,10);

			//所属团队
			$team['sector_id']   = $value['sales_sub_company'];
			$company = M("sector")->field("sector_name,sector_id")->where($team)->find();
			 $value['company_name']   = $company['sector_name'];
			$value['company_id']      = $company['sector_id'];

			//所属经理
			$salesman['user_id'] = $value['sales_manager'];
			$manager = M("user")->field('user_id,nickname as manager_name')->where($salesman)->find();
			$value['manager']    = $manager['manager_name'];
			$value['manager_id'] = $manager['user_id'];
		}
		if($merge_contract){
			if(empty($list))   $res['msg']  = "该客户没有相关合同信息 或 客户ID不正确 !!!";
			$res['rcode'] = 1;
			$res['merge_contract'] = $merge_contract;
		}else{
			$res['msg']   = '所需要的数据不存在!!';
		}
		e_json($res);
	}
	//合并合同
	public function merge_editor(){
		$arr['main']      = I('post.main');
		$arr['stime']     = I('post.stime');
		$arr['etime']     = I('post.etime');
		$arr['mount']     = I('post.mount');
		$arr['product']   = I('post.product');
		$arr['checkbox']  = I('post.checkbox');

		if(count($arr['checkbox']) == 1 && $arr['checkbox'][0] == $arr['main']['contract_id'] ){
			$res['msg']   = "合同不能与自己合并、";
		}elseif(!$arr['checkbox']){
			$res['msg']   = "未勾选要合并的合同信息、";
		}else{
			$res = D("Contract")->merge_editor($arr);
		}
		e_json($res);
	}
	//编辑加载
	public function editor(){
		if (IS_GET){
			$where['contract_id'] = I("contract_id");
			$contract = M("Contract")->alias("c")->field("c.*")->where($where)->find();
		
			$contract['start_time'] = date("Y-m-d",strtotime($contract['start_time'])); 
			$contract['end_time'] = date("Y-m-d",strtotime($contract['end_time']));
			$contract['mount'] = floor($contract['mount']);

			if($contract)
				$res['editor'] = $contract;
			else
				$res['msg'] = "没有找到相关数据!!!";
			e_json($res);
		}
		else { //编辑合同信息
			$res = D("Contract")->editor($_POST);
			e_json($res);
		}
	}
	
	//客户信息监测是否唯一
	public function checkCustomer(){
		$customerId = I("customer_id");
		$where['nickname']    = I("customer_name");
		$where['phone']       = I("customer_phone");
		$where['customer_id'] = array('neq',$customerId);

		$customer = M("customer")->field("customer_id")->where($where)->find();
		$sql = M("customer")->getLastSql();
		if($customer)
			$res['exist'] = true;
		else
			$res['exist'] = false;
		e_json($res);
	}
	
	//客户合同邮寄记录
	public function mail(){
		$order_num = I("order_num");
		if($order_num){
			$sweep['order_num'] = $order_num;
			$contract = M("contract")->field("contract_id")->where($sweep)->find();
		}
		if($contract){
			$where['delivery.source_id'] = $contract['contract_id'];//邮寄条件
			$wheres['pay_record.contract_id']  = $contract['contract_id'];//付款条件
			$maps['contract.contract_id'] = $contract['contract_id'];//详情
		}else{
			$where['delivery.source_id'] = I('contract_id');//邮寄条件
			$wheres['pay_record.contract_id']  = I('contract_id');//付款条件
			$maps['contract.contract_id'] = I('contract_id');//详情
		}

		//客户信息
		$res['customer'] = M("contract")
						    ->field("contract.contract_id,contract.type,contract.type,contract.sales_person,contract.sales_manager,contract.sales_sector,contract.sales_sub_company,contract.mount,contract.start_time,contract.end_time,contract.state,customer.customer_id,customer.nickname as customer_name,customer.phone,product.name")
							->JOIN("LEFT JOIN customer ON contract.customer_id = customer.customer_id")
							->JOIN("LEFT JOIN product ON contract.product_id   = product.product_id")
							->where($maps)
							->find();
		$res['customer']['start_time'] = date("Y-m-d",strtotime($res['customer']['start_time']));
		$res['customer']['end_time']   = date("Y-m-d",strtotime($res['customer']['end_time']));	
		//团队
		$teams['sector_id']   =$res['customer']['sales_sub_company'];
		$companys = M("sector")->field("sector_id,sector_name")->where($teams)->find();
		$res['customer']['company_name']    = $companys['sector_name'];
		$res['customer']['company_id']      = $companys['sector_id'];
		//经理
		$sectors['user_id']   = $res['customer']['sales_manager'];
		$managers = M("user")->field("user_id,nickname")->where($sectors)->find();
		$res['customer']['manager']    = $managers['nickname'];
		$res['customer']['manager_id'] = $managers['user_id'];
		//负责人
		$saless['user_id']    = $res['customer']['sales_person'];
		$users    = M("user")->field("user_id,nickname")->where($saless)->find();
		$res['customer']['user_name']  = $users['nickname'];
		$res['customer']['user_id']    = $users['user_id'];		
		//订单号
		$order['contract_id'] = $res['customer']['contract_id'];
		$pays = M('pay_record')->field('pay_order')->where($order)->find();
		$res['customer']['pay_order'] = $pays['pay_order'];
		//最后一笔邮寄记录
		$res['record']  = M("delivery")->where($where)->order('delivery_id desc')->find();
		//历史邮寄记录
		$delivery       = M("delivery")
						->field("contract.contract_id,contract.order_num as contract_num,contract.sign_status,delivery.*")
						->join("LEFT JOIN  contract ON delivery.source_id = contract.contract_id")
		                ->where($where)
		                ->select();
		foreach($delivery as &$value){
			if(strtotime($value['send_time']) > 0) $value['send_time'] = date("Y-m-d",strtotime($value['send_time']));
			else $value['send_time']  = '';
			if(strstr($value['remark'],',')){
	          $str = explode(",", $value['remark']);
	          if(!preg_match("/[\x7f-\xff]/",$str[0])){
	          	$value['note']        = $str[1];
	          	$value['attribution'] = $str[0];
	          }else{
          		$value['note']        = $str[0];
	          	$value['attribution'] = $str[1];
	          }
	        }else{
	          if(!preg_match("/[\x7f-\xff]/", $value['remark'])) $value['attribution'] = $value['remark'];
	          else $value['note']     = $value['remark'];
	        }
		}
		foreach ($delivery as $k => $val) {
			if(!empty($val['customer_id'])){
				$list[] = $val;
			}
		}
		//付款记录
		$sum = M("pay_record")->field("sum(pay_mount) as mount")->where($wheres)->find();
		$res['sum_money'] = floor($sum['mount']);

		$res['payrecord'] = M("pay_record")
		                  ->field("pay_record.payrecord_id,pay_record.pay_name,pay_record.pay_mount,pay_record.pay_way,pay_record.pay_time,pay_record.sales_sector,pay_record.sales_manager,pay_record.sales_person,pay_record.sales_sub_company,user.nickname as user_name,sector.sector_id,sector.sector_name,contract.is_refund ")
		                  ->join("LEFT JOIN user     ON pay_record.sales_person = user.user_id")
		                  ->join("LEFT JOIN sector   ON pay_record.sales_sector = sector.sector_id")
		                  ->join("LEFT JOIN contract ON pay_record.contract_id  = contract.contract_id")
		                  ->where($wheres)
		                  ->select();
		foreach ($res['payrecord'] as &$values) {
			//团队
			$team['sector_id']  = $values['sales_sub_company'];
			$company = M("sector")->field("sector_name")->where($team)->find();
			$values['company']  = $company['sector_name'];
			//经理
			$sector['user_id']  = $values['sales_manager'];
			$user = M("user") ->field("nickname")->where($sector)->find();
			$values['manager_name'] = $user['nickname'];
			$values['pay_mount']= floor($values['pay_mount']);
			$values['pay_time'] = date("Y-m-d",strtotime($values['pay_time']));
		}

		//退款记录
		$pay['contract_id'] = I('contract_id');
		$pay['record_status'] = 1;
		$retund = M("pay_record")->field("pay_id")->where($wheres)->select();
		if($retund){
			foreach ($retund as $back => $goBack) {
				$refundPays['refund_pays.pay_id'] = $goBack['pay_id'];
				$refund_pays[$back] = M("refund_pays")
									->field("refund.refund_id,refund.create_time,refund.status,refund.sales_id,refund.sales_manager,refund.sales_subcompany,refund_pays.refund_mount")
									->join("LEFT JOIN refund ON refund_pays.refund_id = refund.refund_id")
									->where($refundPays)
									->select();
			}

			foreach ($refund_pays as $part) {
				if(!empty( $part )){
					foreach ($part as $partSubset) {
						if(!empty($partSubset)){
							$partSubset['create_time'] = date("Y-m-d",strtotime($partSubset['create_time']));
							$partSubset['refund_mount'] = floor($partSubset['refund_mount']);
							//业务人员
							$paySale['user_id'] = $partSubset['sales_id'];
							$pay_user = M("user")->field("nickname")->where($paySale)->find();
							$partSubset['user_name'] = $pay_user['nickname'];
							//经理
							$payManager['user_id'] = $partSubset['sales_manager'];
							$pay_manager = M("user")->field("nickname")->where($payManager)->find();
							$partSubset['manager_name'] = $pay_manager['nickname'];
							//团队
							$payCompany['sector_id'] = $partSubset['sales_subcompany'];
							$pay_team = M("sector")->field("sector_name")->where($payCompany)->find();
							$partSubset['company_name'] = $pay_team['sector_name'];
							$res['refund'][] = $partSubset;

						}
					}
				}
			}
		}
		if($list){
			$res['delivery']    = $list;
			$res['rcode']       = 1;
		}else{
			$res['msg']         = '数据为空!!';
		}
		e_json($res);
	}
	//取消合同
	public function cancel(){
		$where['contract_id'] = I("contract_id");
		$map['state'] = -1;
		$contract = M("contract")->where($where)->save($map);
		if($contract){
			$res['rcode'] = 1;
			$res['msg']   = "合同已取消!!!" ;
		}else{
			$res['msg']   = "合同取消失败!!!" ;
		}
		e_json($res);
	}
	//导出合同
	// public function export_contract() {
	// 	$ServiceUser = D("Admin/User","Service","Admin");
	// 	$arr = $ServiceUser->authWithKey($this->m_user['user_id'],'CONTRACT_EXPORT');
	// 	if($arr['rcode'] == 0){
	// 		$res = array('rcode' => 0);
	// 		e_json($res);
	// 	}else{
	// 		$where    = array();
	// 		$where['_string']     = '1=1';
	// 		$where['_string']            = '1=1';
	// 		$where['contract.is_delete'] = array('neq', 1 );
	// 		//搜索条件
	// 		$customer = I('get.customer');
	// 		if($customer && !empty($customer)){
	// 			if(strlen($customer) > 3 && is_numeric($customer))  $maps['customer.phone'] = array('like','%'.$customer.'%');
	// 			$maps['customer.nickname']      = array('like','%'.$customer.'%');
	// 			$maps['customer.customer_code'] = array('like','%'.$customer.'%');
	// 			$maps['_logic']    = 'OR';
	// 			$where['_complex'] = $maps;
	// 		}

	// 		$saless    = I('get.sales');
	// 		if($saless){
	// 			$where['user.nickname'] = array('like','%'.$saless.'%');
	// 		}

	// 		$product  = I('get.product');
	// 		if($product && $product!="-1" ){
	// 			$where['product.product_id'] = $product;
	// 		}

	// 		$stime    = I('get.first_time','','trim');
	// 		$etime    = I('get.second_time','','trim');

	// 		if( $stime && $etime ){
	// 			$stime = date('Y-m-d 00:00:00',strtotime($stime));
	// 			$etime = date('Y-m-d 23:59:59', strtotime($etime));
	// 			if(strtotime($stime) < strtotime($etime)) $where['contract.start_time'] = array('between',array($stime,$etime));
	// 			else $where['contract.start_time'] = array('between',array($etime,$stime));
	// 		}elseif($stime  && !$etime ){
	// 			$stime = date('Y-m-d 00:00:00',strtotime($stime));
	// 			$where['contract.start_time'] =  array('egt',$stime);
	// 		}elseif(!$stime && $etime ){
	// 			$etime = date('Y-m-d 23:59:59', strtotime($etime));
	// 			$where['contract.start_time'] = array('elt', $etime);
	// 		}

	// 		$state = I('get.state');
	// 		if(5== $state || empty( $state)){
	// 			$where['contract.state']  = array('between', array('-2', '5' ) );
	// 		}elseif(6== $state){
	// 			$where['contract.state'] = array('eq', '0' );
	// 		}else{
	// 			$where['contract.state'] = array('eq', $state );
	// 		}
	// 		/*********************************************************/

	// 		$contract = M("contract")
	// 					->field("contract.contract_id,contract.mount,contract.end_time,contract.start_time,contract.state,contract.order_num,contract.address,contract.sales_person,contract.sales_manager,contract.sales_sub_company,contract.second_party_idcard,contract.remark,contract.weigui_status,customer.nickname as customer_name,customer.phone,product.name,contract.first_party_name,contract.first_party_bank_account,contract.first_party_bank_deposit,contract.first_party_address,contract.second_party_name,contract.second_party_phone,contract.second_party_idcard,contract.second_party_address,contract.second_party_email")
	// 					->join("LEFT JOIN customer ON contract.customer_id = customer.customer_id")
	// 					->join("LEFT JOIN product  ON contract.product_id  = product.product_id")
	// 					->join("LEFT JOIN user     ON contract.sales_person= user.user_id")
	// 					->where($where)
	// 					->order("contract.contract_id desc")
	// 					->select();
	// 		import("Common.ORG.Excel");
	// 		$SExcel = new \Common\ORG\Excel();
	// 		$SSheet = new \Common\ORG\Sheet("合同记录");

	// 		$column   = array('签订金额','客户姓名','电话','产品类型','服务期限','合同开始时间','合同是否签好','合同时长','合同编号','邮寄地址','业务员','经理','团队','身份证号','是否违规','违规原因','备注','甲方账户名','账号','开户银行','地址','乙方姓名','身份证号','电话','地址','邮编');
	// 		$SSheet->setColumn( $column );
	// 		foreach($contract as $key =>$val ){
	// 			//合同时长计算
	// 			$length['contract_id'] = $val['contract_id'];
	// 			$length['source_type'] = 1;
	// 			$delivery = M("delivery")->field("status,send_time")->order("delivery_id desc")->find();
	// 			if($delivery['status'] == 2){
	// 				$results = ceil((strtotime($delivery['send_time'])-strtotime($val['start_time']))/(3600*24));
	// 			}elseif($delivery['status'] == 1){
	// 				$results = ceil((strtotime(date("Y-m-d H:i:s"))-strtotime($val['start_time']))/(3600*24));
	// 			}else{
	// 				$results = '';
	// 			}
	// 			//业务员
	// 			$sales['user_id']  = $val['sales_person'];
	// 			$user    = M("user")->field("nickname")->where($sales)->find();
	// 			//经理
	// 			$sector['user_id'] = $val['sales_manager'];
	// 			$manager = M("user")->field("nickname")->where($sector)->find();
	// 			//团队
	// 			$team['sector_id'] = $val['sales_sub_company'];
	// 			$company = M("sector")->field("sector_name")->where($team)->find();

	// 			//违规原因
	// 			$violations['contract_id'] = $val['contract_id'];
	// 			$fine  = M("fine")->field("theme")->where($violations)->order("fine_id")->find();

	// 			if($fine && $fine['theme'] == 1)      $fine['theme'] = '不签署合同';
	// 			elseif($fine && $fine['theme'] == 2)  $fine['theme'] = '暂不寄';
	// 			elseif($fine && $fine['theme'] == 3)  $fine['theme'] = '超龄';
	// 			elseif($fine && $fine['theme'] == 4)  $fine['theme'] = '虚假身份';
	// 			else  $fine['theme'] = '';


	// 			$row   = array();
	// 			$row[] = $val['mount'];
	// 			$row[] = $val['customer_name'];
	// 			$row[] = ' '.$val['phone'];
	// 			$row[] = $val['name'];
	// 			$row[] = date("Y-m-d",strtotime($val['end_time']));
	// 			$row[] = date("Y-m-d",strtotime($val['start_time']));
	// 			$row[] = $val['state'] == 1?'已签好':($val['state'] == 3?'已签好':'未知');
	// 			$row[] = $results;//时长计算
	// 			$row[] = $val['order_num'];
	// 			$row[] = $val['address'];
	// 			$row[] = $user['nickname'];//业务员
	// 			$row[] = $manager['nickname'];//经理
	// 			$row[] = $company['sector_name'];//团队
	// 			$row[] = $val['second_party_idcard'];
	// 			$row[] = $val['weigui_status'] == 0?'未知':($val['weigui_status'] == 21?'不违规':($val['weigui_status'] == 11?'违规未导出':'违规已导出'));
	// 			$row[] = $fine['theme'];//违规原因
	// 			$row[] = $val['remark'];

	// 			$row[] = $val['first_party_name'];
	// 			$row[] = $val['first_party_bank_account'];
	// 			$row[] = $val['first_party_bank_deposit'];
	// 			$row[] = $val['first_party_address'];
	// 			$row[] = $val['second_party_name'];
	// 			$row[] = ' '.$val['second_party_idcard'];
	// 			$row[] = ' '.$val['second_party_phone'];
	// 			$row[] = $val['second_party_address'];
	// 			$row[] = $val['second_party_email'];

	// 			$SSheet->addRow( $row );
	// 		}
	// 		$exportData = $SExcel->add_sheet( $SSheet)->export_sheet("合同数据导出");
	// 		if( $exportData['rcode'] ){
	// 			$exportData['name'] = basename( $exportData['data']['view_path'] );
	// 			$exportData['excel'] = file_get_contents( $exportData['data']['real_path'] );
	// 			echo $exportData['excel'];
	// 			exit();
	// 		}
	// 	}
	// }
	//导出违规
	public function export_violations(){
		$where['contract.is_delete'] = 0;
		$where['contract.weigui_status'] = 11;
	  	$arr = M("contract")
           ->field("contract.order_num,contract.contract_id,contract.mount,contract.start_time,contract.sales_person,contract.sales_manager,contract.sales_sub_company,customer.nickname as customer_name,fine.theme,fine_user.fine_mount")
          ->join("LEFT JOIN customer  ON contract.customer_id = customer.customer_id ")
          ->join("LEFT JOIN fine      ON contract.contract_id = fine.contract_id ")
          ->join("LEFT JOIN fine_user ON fine.fine_id = fine_user.fine_id ")
          ->where($where)
          ->select();
		import("Common.ORG.Excel");
		$SExcel = new \Common\ORG\Excel();
		$SSheet = new \Common\ORG\Sheet("违规记录");

		$headline = array('合同编号','违规业绩客户','违规金额(元)','合同开始时间','业务员','经理','团队','违规原因');
		$SSheet->setColumn( $headline );

		foreach ($arr as &$value) {
	        //负责人
	        $sales['user_id']   = $value['sales_person'];
	        $user    = M("user")->field("nickname")->where($sales)->find();
	        //经理
	        $sector['user_id']  = $value['sales_manager'];
	        $manager = M("user")->field("nickname")->where($sector)->find();
	        //团队
	        $team['sector_id']  = $value['sales_sub_company'];
	        $company = M("sector")->field("sector_name")->where($team)->find();

	        if($value['theme'] == 1)      $value['theme'] = '不签署合同';
			elseif($value['theme'] == 2)  $value['theme'] = '暂不寄';
			elseif($value['theme'] == 3)  $value['theme'] = '超龄';
			elseif($value['theme'] == 4)  $value['theme'] = '虚假身份';
			else  $value['theme'] = '';


	        $row     = array();
	        $row[]   = $value['order_num'];
	        $row[]   = $value['customer_name'];
	        $row[]   = floor($value['fine_mount']);
	        $row[]   = date("Y-m-d",strtotime($value['start_time']));
	        $row[]   = $user['nickname'];
	        $row[]   = $manager['nickname'];
	    	$row[]   = $company['sector_name'];
	        $row[]   = $value['theme'] ;

	        //更改违规状态
	        $wheres['contract_id'] = $value['contract_id'];
	        $maps['weigui_status'] = 12;
	        M("contract")->where($wheres)->save($maps);

	    	$SSheet->addRow( $row );
      	}

      	$exportData = $SExcel->add_sheet( $SSheet)->export_sheet("数据导出");
      	if( $exportData['rcode'] ){
	        $exportData['name'] = basename( $exportData['data']['view_path'] );
	        $exportData['excel'] = file_get_contents( $exportData['data']['real_path'] );
	        echo $exportData['excel'];
	        exit();
      	}
	}
	//合同批量编辑
	public function batch_editor(){
		foreach ($_POST['batch'] as $key => $value) {
			$map['recipients']    = $value['recipients'];
			$map['phone']         = $value['phone'];
			$map['address']       = $value['address'];
			$map['customer_id']   = $value['customer_id'];
			$map['source_id']     = $value['contract_id'];
			$map['source_type']   = 1;

			$map['sales_id']	  = $value['sales_person'];
			$map['sales_sector']  = $value['sales_sector'];
			$map['sales_manager'] = $value['sales_manager'];
			$map['sales_subcompany'] = $value['sales_sub_company'];
			$map['create_time']   = $value['send_time']." ".date("H:i:s");
			$map['remark']        = $value['remark'];
			$map['status']        = 10;
			$map['is_export']     = 0;
			$add  = M("delivery")->add($map);

			if($add){
				$where['contract_id'] = $value['contract_id'];
				$maps['sign_status']  = 2;
				$contract = M("contract")->where($where)->save($maps);
			}else{
				 $failure[]  = $value['customer_nickname'];
			}
		}
		if(!empty( $failure )) $res['failure'] = implode(' 、',$failure);
		$res['msg']   = "信息编辑成功!";
		$res['rcode'] = 1;
		e_json($res);
	}
	//公用数据
	public function productData(){
		//权限判断
		$ServiceUser = D("Admin/User","Service","Admin");
		$arr = $ServiceUser->authWithKey($this->m_user['user_id'],'DATA_ADMIN');
		//产品检索
		$res['product'] = list_to_product($this->m_user,$arr['rcode']);
		//今日日期
		$res['today']   = date('Y-m-d');
		e_json($res);
	}

	private function _findContractWithId( $param )
	{
		if (!$param)
			return false;
		$MContract  = D('Admin/Contract');
		$where = array();
		$find = false;
		if( $param && ( is_string($param)||is_int($param)  ) ) {
			$where['c.contract_id'] = array('eq', $param);
			$find = true;
		}
		else
			$where['c.contract_id'] = array('in', $param);
		//查询内容
		$fields = 'c.second_party_phone as phone,c.second_party_name as nickname,u.nickname as sales,s.sector_name as team,c.state,c.mount,
									c.start_time,c.end_time,c.contract_id,c.backcontract as view_url,p.name as product,c.sign_status';
		$data = $MContract->alias("c")
						  ->field( $fields )
						  ->join("LEFT JOIN user u on c.sales_person=u.user_id")
						  ->join("LEFT JOIN sector s on s.sector_id=c.sales_sub_company")
						  ->join("LEFT JOIN customer cu on c.customer_id=cu.customer_id")
						  ->join("LEFT JOIN product p on p.product_id=c.product_id")
						  ->where( $where )
						  ->order("c.start_time desc")
						  ->select();
		return $data&&$find ? $data[0] : $data;
	}

	//电子合同
	public function econtract()
	{
		$res = array('rcode'=>0, 'msg'=> '', 'data'=> array() );
		
		if (IS_GET) {
			$Mdo = D('Admin/Contract');
			$where = array();
			$contract_id = I('get.contract_id', 0, 'intval');
			$where['c.contract_id'] = array('eq', $contract_id);
			$data = $Mdo->alias("c")->where( $where )->find();
			if ($data) {
				$contract_id = I('get.contract_id', 0, 'intval');
				$data = $this->_findContractWithId( $contract_id );
				if ($data) {
					$res['rcode'] = 1;
					$res['msg'] = 'OK';
					$res['data'] = $data;
				}
				else 
					$res['msg'] = "合同数据不存在";
			}
			else 
				$res['msg'] = "合同数据不存在";
		}
		else if(IS_POST) {
			$contract_id = I('post.contract_id', 0, 'intval');
			$Mdo = D('Admin/Contract');
			$wheres = array();
			$wheres['contract_id'] = array('eq', $contract_id);
			$find = $Mdo->where( $wheres )->find();
			$res['contract_id'] = $contract_id;
			if ($find) {
				$EContractService = D('Admin/Econtract', 'Service');
				$ret = $EContractService->post( $contract_id );
				$res['fix'] = $ret;
				if ($ret['rcode']) {
					$res['rcode'] =1;
					$res['msg'] = 'OK';
					$res['data'] = $ret['data'];
				}
				else {
					$res['msg'] = $ret['msg'];
				}
			}
			else {
				$res['msg'] = "合同状态已经变更，不能发起电子合同";
			}
		}

		e_json($res);
	}

	//批量电子合同问题
	public function batchEcontract()
	{
		$res = array('rcode'=>0, 'msg'=> '', 'data'=> array() );
		$MContract = D('Admin/Contract');
		$MService = D('Admin/Econtract', 'Service');
		if (IS_POST) {
			$where =  array();
			$api = I('post.api', 'load', 'trim');
			$api = strtolower( $api );
			$data = I('post.data');
			if (!$data || !is_array($data) || (is_array($data)&&!count($data)) ) {
				$res['msg'] = "提交参数错误";
			}
			if ('load' == $api) {
				$findData = $this->_findContractWithId( $data );
				if ($findData) {
					$res['rcode'] = 1;
					$res['msg'] = 'OK';
					$res['data'] = $findData;
				}
				else {
					$res['msg'] = "获取合同数据失败";
				}
			}
 		}

		e_json( $res );
	}
}
